package com.blb.goods_service.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blb.goods_service.entity.Category;
import com.blb.goods_service.entity.CategoryBO;
import com.blb.goods_service.entity.JsonResult;
import com.blb.goods_service.entity.TreeVO;
import com.blb.goods_service.service.ICategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Api
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private ICategoryService categoryService;

    /**
     * 查询所有子分类
     */
    @ApiOperation("根据父id查询分类")
    @GetMapping("/parent/{pid}")
    public JsonResult findCategoriesByParentId(@PathVariable("pid")Integer pid){
        try {
            List<Category> list = categoryService.list(new QueryWrapper<Category>()
                    .lambda()
                    .eq(Category::getParentId, pid));
            List<TreeVO> tree = new ArrayList<>();
            list.forEach(category -> {
                tree.add(new TreeVO(category.getId(),category.getName(),category.getId()));
            });
            return new JsonResult(1,tree);
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(0,null);
        }
    }

    /**
     * 保存分类
     * @param categoryBO
     * @return
     */
    @ApiOperation("保存")
    @PostMapping
    public JsonResult saveCategory(@RequestBody CategoryBO categoryBO){
        try {
            System.out.println(categoryBO.getName());
            System.out.println(categoryBO.getParentId());
            System.out.println(categoryBO);
            Category category = categoryService.saveCategory(categoryBO);
            return new JsonResult(1,category);
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(0,null);
        }
    }


}
